import {access, constants, writeFile} from 'fs/promises'
import {NextRequest, NextResponse} from 'next/server'
import {readdir} from "node:fs/promises";
import {getUserFromSession} from "@/lib/auth";
import {createVideo, execJpg} from "@/lib/video";
import {exec} from "child_process";

export async function POST(request: NextRequest, response: NextResponse) {
    const user = await getUserFromSession()
    if (!user) {
        return NextResponse.json({success: false, error: '请先登录'})
    }

    // save
    const data = await request.formData()
    const file: File | null = data.get('file') as unknown as File

    if (!file) {
        return NextResponse.json({success: false, error: 'No file uploaded'})
    }
    // video/* audio/* image/*
    if (file.type !== 'video/mp4') {
        return NextResponse.json({success: false, error: 'The file type is not support'})
    }

    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)

    // todo: 文件名随机编码, 防止重复
    // 这里是你要进行保存的文件目录地址
    const path = `./public/videos/${file.name}`
    const files = await readdir('./public/videos')
    const videos = files.filter((f) => f.endsWith('.mp4'))
    // 防止同名(如果文件名编码,则失效) 用别的方法比较文件(同文件就不上传, 用以前的)
    for (const v of videos) {
        if (v === file.name) {
            return NextResponse.json({success: false, error: 'The file already exist'})
        }
    }
    await writeFile(path, buffer)
    // 生成视频封面
    // 视频的路径
    const realPath = `F:\\codes\\projs\\bilibili\\bili-web\\public\\videos\\${file.name}`
    // 存入封面的路径
    const coverPath = `F:\\codes\\projs\\bilibili\\bili-web\\public\\videos\\${file.name}-cover.jpg`
    const coverDBPath = `/videos/${file.name}-cover.jpg`// 存入数据库, 从静态资源服务获取cover的url
    try {
        await execJpg(realPath, coverPath)
    } catch (e) {
        return NextResponse.json({success: false, error: "生成封面失败"})
    }

    // 保存信息到数据库
    try {
        await createVideo({
            name: file.name,
            userId: user.id,
            cover: coverDBPath
        })
    } catch (err) {
        return NextResponse.json({success: false, error: err.message})
    }

    console.log(`open ${path} to see the uploaded file`)

    return NextResponse.json({success: true})
}